package cn.itcast.nems.common.web.interceptor;

import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.account.AccountInfo;
import cn.itcast.nems.common.web.util.JwtTokenUtil;
import cn.itcast.nems.employee.service.EmployeeGroupService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
@RequiredArgsConstructor
public class AccountInterceptor implements HandlerInterceptor {
    private final String HEADER_CURRENT_ACCOUNT = "itcastConsoleUser";
    private final String AUTHORIZATION = "Authorization";
    private final ObjectMapper objectMapper = new ObjectMapper();

    private final EmployeeGroupService employeeGroupService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        wrapperContext(request);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        AccountHolder.clear();
    }

    private void wrapperContext(HttpServletRequest request) {
        final String jwtToken = request.getHeader(AUTHORIZATION);
        if (StringUtils.hasText(jwtToken)) {
            final AccountInfo info = JwtTokenUtil.parseToken(jwtToken);
            AccountHolder.setAccountInfo(info);
            AccountHolder.setAccount(info.getEmail());
            AccountHolder.setAccountEmployeeGroups(employeeGroupService.getEmployeeGroups(info.getEmail()));
        } else {
            String accountStr = request.getHeader(HEADER_CURRENT_ACCOUNT);
            if (!StringUtils.hasText(accountStr)) {
                return;
            }

            try {
                // {"account":"useremail@itcast.cn"}
                final JsonNode jsonNode = objectMapper.readTree(accountStr);
                AccountHolder.setAccount(jsonNode.get("account").asText());
            } catch (JsonProcessingException e) {
                log.error("当前账户信息格式转换错误！", e);
            }
        }
    }
}
